package com._101aiot.auth.init;

import com._101aiot.auth.entity.AuthResourceRoleDO;
import com._101aiot.auth.service.AuthResourceRoleService;
import com._101aiot.redis.core.RedisService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 初始化资源与角色匹配关系到redis，方便网关服务进行鉴权的时候获取
 * 数据源：数据库存储
 * 缓存：redis
 * 影响范围：gateway,全局资源
 *
 * @author xionggd
 */
@Component
@AllArgsConstructor
@Slf4j
public class InitResourceRole {

    private final AuthResourceRoleService authResourceRoleService;

    private final RedisService redisService;

    /**
     * 初始化资源角色对应关系到Redis
     */
    @PostConstruct
    public void initResourceRoleToRedis() {
        List<AuthResourceRoleDO> all = authResourceRoleService.findAll();
        Map<String, List<String>> resourceRolesMap = new TreeMap<>();
        all.forEach(i -> resourceRolesMap.put(i.getApi(), Arrays.asList(i.getRole().split("[,]"))));
        Boolean b = redisService.hashMapSet("AUTH:RESOURCE_ROLES_MAP", resourceRolesMap);
        log.info("从数据库初始资源角色对应关系到redis中：{}", b);
    }

}

